package cn.Y_Qiu.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

// 交给容器管理
@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 通过请求头获取名为token的数据
        String token = request.getHeader("token");
        System.out.println(token);
        if(!StringUtils.isEmpty(token)){
            // 获取redis内值
            Object o = redisTemplate.opsForValue().get(token);
            if (o != null){
                // 重置过期时间为30mins
                redisTemplate.opsForValue().set("token", o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //返回一个错误json，让前端跳页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //{"success":false,"message":"unlogin"}，
        writer.write("{\"success\":false,\"message\":\"unlogin\"} ");
        writer.close();
        return false;
    }
}
